<template>
  <div class="inspection-container">
    <el-card class="inspection-card">
      <template #header>
        <div class="card-header">
          <h3>宿舍内务检查记录</h3>
          <el-button type="primary" @click="getInspectionList" :loading="loading">
            <el-icon><RefreshRight /></el-icon> 刷新数据
          </el-button>
        </div>
      </template>

      <!-- 搜索过滤 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="检查时间">
            <el-date-picker
              v-model="searchForm.jianchashijian"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="宿管姓名">
            <el-input v-model="searchForm.suguanxingming" placeholder="请输入宿管姓名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 检查记录列表 -->
      <el-table
        v-loading="loading"
        :data="inspectionList"
        style="width: 100%"
        border
      >
        <el-table-column prop="jianchabianhao" label="检查编号" width="120"></el-table-column>
        <el-table-column prop="loudong" label="楼栋" width="100"></el-table-column>
        <el-table-column prop="sushe" label="宿舍号" width="100"></el-table-column>
        <el-table-column prop="jianchapingfen" label="检查评分" width="100">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.jianchapingfen)">{{ scope.row.jianchapingfen }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="jianchashijian" label="检查时间" width="120"></el-table-column>
        <el-table-column prop="suguanxingming" label="检查人" width="100"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="page"
          :page-size="limit"
          :total="total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="检查详情"
      width="50%"
      destroy-on-close
    >
      <div class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="检查编号">{{ currentDetail.jianchabianhao }}</el-descriptions-item>
          <el-descriptions-item label="检查时间">{{ currentDetail.jianchashijian }}</el-descriptions-item>
          <el-descriptions-item label="楼栋">{{ currentDetail.loudong }}</el-descriptions-item>
          <el-descriptions-item label="宿舍号">{{ currentDetail.sushe }}</el-descriptions-item>
          <el-descriptions-item label="检查评分" :span="2">
            <el-progress 
              :percentage="currentDetail.jianchapingfen" 
              :status="getProgressStatus(currentDetail.jianchapingfen)">
            </el-progress>
          </el-descriptions-item>
          <el-descriptions-item label="检查人">{{ currentDetail.suguanxingming }}</el-descriptions-item>
          <el-descriptions-item label="备注" v-if="currentDetail.beizhu" :span="2">
            {{ currentDetail.beizhu }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="inspection-tips" v-if="currentDetail.jianchapingfen < 60">
          <el-alert
            title="温馨提示"
            type="warning"
            description="您的宿舍卫生评分不合格，请及时整改！"
            show-icon
            :closable="false"
          ></el-alert>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { RefreshRight } from '@element-plus/icons-vue'

// 数据列表
const inspectionList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const autoRefreshTimer = ref(null)

// 详情对话框控制
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 搜索表单
const searchForm = reactive({
  jianchashijian: '',
  suguanxingming: ''
})

// 学生信息
const studentInfo = ref({
  xueshengzhanghao: '',
  sushe: '',
  loudong: ''
})

// 初始化加载数据
onMounted(async () => {
  // 获取学生宿舍号和楼栋号，然后获取检查列表
  loading.value = true
  try {
    await getStudentDormitoryInfo()
  } catch (error) {
    console.error('获取学生信息失败:', error)
  } finally {
    loading.value = false
  }
  
  // 获取检查列表
  getInspectionList()
  
  // 设置自动刷新定时器 (每60秒刷新一次)
  autoRefreshTimer.value = setInterval(() => {
    getInspectionList(false)
  }, 60000)
})

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value)
  }
})

// 获取学生宿舍号和楼栋号信息
const getStudentDormitoryInfo = async () => {
  try {
    const xueshengzhanghao = localStorage.getItem('adminName')
    if (!xueshengzhanghao) return

    // 从学生表获取宿舍信息
    const response = await axios.get('/springbootyyh3w/xuesheng/page', {
      params: { 
        xueshengzhanghao,
        page: 1,
        limit: 1
      },
      headers: {
        'Token': localStorage.getItem('Token')
      }
    })
    
    if (response.data.code === 0 && response.data.data.list && response.data.data.list.length > 0) {
      const studentData = response.data.data.list[0]
      console.log('获取到学生信息:', studentData)
      
      // 更新学生信息
      studentInfo.value = {
        xueshengzhanghao: studentData.xueshengzhanghao || '',
        sushe: studentData.sushe || '',
        loudong: studentData.loudong || ''
      }
      
      // 存储宿舍信息用于后续使用
      localStorage.setItem('sushe', studentInfo.value.sushe)
      localStorage.setItem('loudong', studentInfo.value.loudong)
      
      // 打印学生宿舍信息
      console.log('学生宿舍信息:', studentInfo.value)
    }
  } catch (error) {
    console.error('获取学生宿舍信息失败:', error)
  }
}

// 获取检查记录列表
const getInspectionList = async (showLoading = true) => {
  if (showLoading) {
    loading.value = true
  }
  
  try {
    // 如果没有宿舍信息，再尝试获取一次
    if (!studentInfo.value.sushe) {
      await getStudentDormitoryInfo()
      
      // 如果仍然没有宿舍信息，显示提示
      if (!studentInfo.value.sushe) {
        ElMessage.warning('未找到您的宿舍信息，请联系管理员')
        loading.value = false
        return
      }
    }
    
    // 准备查询参数
    const params = {
      page: page.value,
      limit: limit.value,
      // 始终使用楼栋和宿舍号
      loudong: studentInfo.value.loudong,
      sushe: studentInfo.value.sushe
    }
    
    // 如果有宿管姓名筛选条件，则添加
    if (searchForm.suguanxingming && searchForm.suguanxingming.trim() !== '') {
      params.suguanxingming = searchForm.suguanxingming
    }
    
    // 如果有检查时间筛选条件，则添加日期范围参数
    if (searchForm.jianchashijian && searchForm.jianchashijian.trim() !== '') {
      params.jianchashijian = searchForm.jianchashijian
    }
    
    console.log('查询内务检查记录参数:', params)
    
    const response = await axios.get('/springbootyyh3w/weishengjiancha/page', {
      params,
      headers: {
        'Token': localStorage.getItem('Token')
      }
    })
    
    if (response.data.code === 0) {
      inspectionList.value = response.data.data.list
      total.value = response.data.data.total
      
      // 检查是否有数据，如果没有，显示友好提示
      if (inspectionList.value.length === 0 && showLoading) {
        ElMessage.info('未查询到您宿舍的内务检查记录')
      }
      
      // 如果是后台自动刷新，显示提示
      if (!showLoading && response.data.data.list.length > 0 && 
          (!inspectionList.value.length || 
           response.data.data.list[0].id !== inspectionList.value[0].id)) {
        ElMessage.success('检查记录已更新')
      }
    } else {
      if (showLoading) {
        ElMessage.error(response.data.msg || '获取检查记录失败')
      }
    }
  } catch (error) {
    console.error('获取检查记录列表出错:', error)
    if (showLoading) {
      ElMessage.error('获取检查记录失败，请检查网络连接')
    }
    // 出错时清空数据
    inspectionList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  page.value = 1
  getInspectionList()
}

// 分页事件处理
const handleCurrentChange = (val) => {
  page.value = val
  getInspectionList()
}

// 根据评分获取标签类型
const getScoreTagType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return ''
  if (score >= 60) return 'warning'
  return 'danger'
}

// 根据评分获取进度条状态
const getProgressStatus = (score) => {
  if (score >= 90) return 'success'
  if (score >= 60) return ''
  return 'exception'
}

// 查看详情
const viewDetail = async (row) => {
  try {
    const response = await axios.get(`/springbootyyh3w/weishengjiancha/detail/${row.id}`, {
      headers: {
        'Token': localStorage.getItem('Token')
      }
    })
    
    if (response.data.code === 0) {
      currentDetail.value = response.data.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情出错:', error)
    ElMessage.error('获取详情失败，请检查网络连接')
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.jianchashijian = ''
  searchForm.suguanxingming = ''
  getInspectionList()
}
</script>

<style scoped>
.inspection-container {
  padding: 20px;
}

.inspection-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-container {
  padding: 10px;
}

.inspection-tips {
  margin-top: 20px;
}
</style> 
